using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Reflection.Emit;

class MainModule
{
	static int Main(string[] args)
	{
		// Parse the command line.
		CommandLine cl;
		try
		{ cl = new CommandLine(args); }
		catch (ArgumentException ex)
		{ return CommandLine.ShowUsage(ex.Message); }

		if (!File.Exists(cl.SourcePath))
		{
            Console.Error.WriteLine("The system cannot find the file specified.");
            return 2;//fnf
		}

		// Prepare an assemblyname for compilation.
		AssemblyName assemname = new AssemblyName();
        if (cl.OutputPath != null)
            assemname.Name = Path.GetFileNameWithoutExtension(cl.OutputPath);
        else
            assemname.Name = Path.GetFileNameWithoutExtension(cl.SourcePath);

		// Parse the source file -- extract regexes, and version/keypair attributes.
		RegexCompilationInfo[] regexinfos;
		CustomAttributeBuilder[] custattrs;

		CodeParser cp = new CodeParser(cl.SourcePath);
		cp.ParseSourceFile(assemname, out regexinfos, out custattrs);

		// Move to the desired target directory (if specified).
		string cwd = Environment.CurrentDirectory;

		try // to remember to restore cwd
		{
			if (cl.OutputPath != null)
			{
				string outdir = Path.GetDirectoryName(cl.OutputPath);
				if (outdir.Length != 0) Environment.CurrentDirectory = outdir;
			}

			// Compile!
			Regex.CompileToAssembly(regexinfos,assemname,custattrs);
		}
		finally
		{
			// Restore the cwd.
			Environment.CurrentDirectory = cwd;
		}

		// We made it.
		return 0;//ok
	}
}
